$(function() {

	// init date tables
	var jobTable = $("#timingStrategy_list").dataTable({
		"deferRender": true,
		"processing" : true,
	    "serverSide": true,
		"ajax": {
			url: base_url + "/jobTimingStrategy/findQuartzListByPage",
			type:"post",
	        data : function ( d ) {
	        	var obj = {};
	        	obj.page = d.start;
	        	obj.rows = d.length;
                return obj;
            }
	    },
	    "searching": false,
	    "ordering": false,
	    //"scrollX": true,	// scroll x，close self-adaption
	    "columns": [
	                {
	                	"data": 'id',
						"bSortable": false,
						"visible" : false,
						"width":'7%'
					},
	                {
	                	"data": 'description',
						"visible" : true,
						"width":'25%'
					},
					{
						"data": 'cron',
						"visible" : true,
						"width":'13%'
					},
	                {
	                	"data": 'addTime',
	                	"visible" : true,
						"width":'13%',
	                	"render": function ( data, type, row ) {
	                		return data?moment(new Date(data)).format("YYYY-MM-DD HH:mm:ss"):"";
	                	}
	                },
	                {
	                	"data": 'editTime',
	                	"visible" : true,
						"width":'13%',
	                	"render": function ( data, type, row ) {
	                		return data?moment(new Date(data)).format("YYYY-MM-DD HH:mm:ss"):"";
	                	}
	                },
			{
				"data": I18n.system_opt ,
				"width":'15%',
				"render": function ( data, type, row ) {
					return function(){
						// data
						tableData['key'+row.id] = row;

						// opt
						var html = '<div class="btn-group">\n' +
							'     <button type="button" class="btn btn-primary btn-sm">'+ I18n.system_opt +'</button>\n' +
							'     <button type="button" class="btn btn-primary btn-sm dropdown-toggle" data-toggle="dropdown">\n' +
							'       <span class="caret"></span>\n' +
							'       <span class="sr-only">Toggle Dropdown</span>\n' +
							'     </button>\n' +
							'     <ul class="dropdown-menu" role="menu" _id="'+ row.id +'" >\n' +
							'       <li><a href="javascript:void(0);" class="opt_edit" >'+ I18n.system_opt_edit +'</a></li>\n' +
							'       <li><a href="javascript:void(0);" class="opt_del" >'+ I18n.system_opt_del +'</a></li>\n' +
							'     </ul>\n' +
							'   </div>';

						return html;
					};
				}
			}
	            ],
		"language" : {
			"sProcessing" : I18n.dataTable_sProcessing ,
			"sLengthMenu" : I18n.dataTable_sLengthMenu ,
			"sZeroRecords" : I18n.dataTable_sZeroRecords ,
			"sInfo" : I18n.dataTable_sInfo ,
			"sInfoEmpty" : I18n.dataTable_sInfoEmpty ,
			"sInfoFiltered" : I18n.dataTable_sInfoFiltered ,
			"sInfoPostFix" : "",
			"sSearch" : I18n.dataTable_sSearch ,
			"sUrl" : "",
			"sEmptyTable" : I18n.dataTable_sEmptyTable ,
			"sLoadingRecords" : I18n.dataTable_sLoadingRecords ,
			"sInfoThousands" : ",",
			"oPaginate" : {
				"sFirst" : I18n.dataTable_sFirst ,
				"sPrevious" : I18n.dataTable_sPrevious ,
				"sNext" : I18n.dataTable_sNext ,
				"sLast" : I18n.dataTable_sLast
			},
			"oAria" : {
				"sSortAscending" : I18n.dataTable_sSortAscending ,
				"sSortDescending" : I18n.dataTable_sSortDescending
			}
		}
	});
	// table data
	var tableData = {};
	// search btn
	$('#searchBtn').on('click', function(){
		jobTable.fnDraw();
	});

	$('.add').on('click', function(){
		$("#addModal .form .form-group .input-group").remove();
		$("#addModal .form input[name='cronConf']").cronGen({});
		$('#addModal').modal({backdrop: false, keyboard: false}).modal('show');
	});
	var icon = "<i class='fa fa-times-circle'></i> ";
	var addModalValidate = $("#addModal .form").validate({
		errorElement : 'span',
		errorClass : 'help-block',
		focusInvalid : true,
		rules: {
			description: {
				required: true
			},
			cronConf: {
				required: true
			}
		},
		messages: {
			description: {
				required: icon + "请输入执行策略名称"
			},
			cronConf: {
				required: icon + "请选择cron编码"
			}
		},
		highlight : function(element) {
			$(element).closest('.form-group').addClass('has-error');
		},
		success : function(label) {
			label.closest('.form-group').removeClass('has-error');
			label.remove();
		},
		errorPlacement : function(error, element) {
			element.parent('div').append(error);
		},
		submitHandler : function(form) {
			var scheduleConf = $("#addModal .form input[name='cronGen_display']").val();
			console.log(scheduleConf);
			$("#addModal .form input[name='cron']").val(scheduleConf );
			$.post(base_url + "/jobTimingStrategy/save",  $("#addModal .form").serialize(), function(data, status) {
				if (data.code == "200") {
					$('#addModal').modal('hide');
					layer.open({
						title: I18n.system_tips ,
						btn: [ I18n.system_ok ],
						content: I18n.system_add_suc ,
						icon: '1',
						end: function(layero, index){
							jobTable.fnDraw();
						}
					});
				} else {
					layer.open({
						title: I18n.system_tips,
						btn: [ I18n.system_ok ],
						content: (data.msg || I18n.system_add_fail  ),
						icon: '2'
					});
				}
			});
		}
	});
	$("#addModal").on('hide.bs.modal', function () {
		$("#addModal .form")[0].reset();
		addModalValidate.resetForm();
		$("#addModal .form .form-group").removeClass("has-error");
	});
	// opt_edit
	$("#timingStrategy_list").on('click', '.opt_edit',function() {
		var id = $(this).parents('ul').attr("_id");
		var row = tableData['key'+id];
		$("#updateModal .form input[name='id']").val( row.id );
		$("#updateModal .form input[name='description']").val( row.description );
		$("#updateModal .form input[name='cron']").val( row.cron );
		$("#updateModal .form .form-group .input-group").remove();
		$("#updateModal .form input[name='cronConf']").val( row.cron );
		$("#updateModal .form input[name='cronConf']").cronGen({});


		$('#updateModal').modal({backdrop: false, keyboard: false}).modal('show');
	});
	var updateModalValidate = $("#updateModal .form").validate({
		errorElement : 'span',
		errorClass : 'help-block',
		focusInvalid : true,
		rules: {
			description: {
				required: true
			},
			cron: {
				required: true
			}
		},
		messages: {
			description: {
				required: icon + "请输入执行策略名称"
			},
			cron: {
				required: icon + "请选择cron编码"
			}
		},
		highlight : function(element) {
			$(element).closest('.form-group').addClass('has-error');
		},
		success : function(label) {
			label.closest('.form-group').removeClass('has-error');
			label.remove();
		},
		errorPlacement : function(error, element) {
			element.parent('div').append(error);
		},
		submitHandler : function(form) {
			var scheduleConf = $("#updateModal .form input[name='cronGen_display']").val();
			$("#updateModal .form input[name='cron']").val(scheduleConf );
			$.post(base_url + "/jobTimingStrategy/update",  $("#updateModal .form").serialize(), function(data, status) {
				if (data.code == "200") {
					$('#updateModal').modal('hide');

					layer.open({
						title: I18n.system_tips ,
						btn: [ I18n.system_ok ],
						content: I18n.system_update_suc ,
						icon: '1',
						end: function(layero, index){
							jobTable.fnDraw();
						}
					});
				} else {
					layer.open({
						title: I18n.system_tips,
						btn: [ I18n.system_ok ],
						content: (data.msg || I18n.system_update_fail  ),
						icon: '2'
					});
				}
			});
		}
	});
	$("#updateModal").on('hide.bs.modal', function () {
		$("#updateModal .form")[0].reset();
		addModalValidate.resetForm();
		$("#updateModal .form .form-group").removeClass("has-error");
	});
	// opt_del
	$("#timingStrategy_list").on('click', '.opt_del',function() {
		var id = $(this).parents('ul').attr("_id");

		layer.confirm( (I18n.system_ok + "删除此定时策略吗？") , {
			icon: 3,
			title: I18n.system_tips ,
			btn: [ I18n.system_ok, I18n.system_cancel ]
		}, function(index){
			layer.close(index);

			$.ajax({
				type : 'POST',
				url : base_url + '/jobTimingStrategy/remove',
				data : {"id":id},
				dataType : "json",
				success : function(data){
					if (data.code == 200) {
						layer.open({
							title: I18n.system_tips ,
							btn: [ I18n.system_ok ],
							content: ("删除定时策略" + I18n.system_success),
							icon: '1',
							end: function(layero, index){
								jobTable.fnDraw();
							}
						});
					} else {
						layer.open({
							title: I18n.system_tips,
							btn: [ I18n.system_ok ],
							content: (data.msg || ("删除定时策略" + I18n.system_fail)),
							icon: '2'
						});
					}
				},
			});
		});
	});
});
